from PyQt5.QtWidgets import (
    QWidget, QHBoxLayout, QVBoxLayout, QCheckBox,
    QLabel, QPushButton, QFrame, QSizePolicy
)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont, QPalette
from models.task import Task, Priority, TaskStatus


class TaskItem(QFrame):
    """任务项组件"""
    
    # 信号定义
    task_toggled = pyqtSignal(str)  # 任务状态切换
    task_edit_requested = pyqtSignal(str)  # 请求编辑任务
    task_delete_requested = pyqtSignal(str)  # 请求删除任务
    
    def __init__(self, task: Task, parent=None):
        super().__init__(parent)
        self.task = task
        self.init_ui()
        self.setup_connections()
        self.update_appearance()
    
    def init_ui(self):
        """初始化用户界面"""
        self.setFrameStyle(QFrame.StyledPanel)
        self.setLineWidth(1)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        # 主布局
        main_layout = QHBoxLayout()
        main_layout.setContentsMargins(10, 8, 10, 8)
        
        # 复选框
        self.checkbox = QCheckBox()
        self.checkbox.setChecked(self.task.status == TaskStatus.COMPLETED)
        main_layout.addWidget(self.checkbox)
        
        # 任务信息区域
        info_layout = QVBoxLayout()
        info_layout.setSpacing(2)
        
        # 标题和优先级布局
        title_layout = QHBoxLayout()
        title_layout.setSpacing(8)
        
        # 任务标题
        self.title_label = QLabel(self.task.title)
        self.title_label.setWordWrap(True)
        title_font = QFont()
        title_font.setPointSize(10)
        title_font.setBold(True)
        self.title_label.setFont(title_font)
        title_layout.addWidget(self.title_label)
        
        # 优先级标签
        self.priority_label = QLabel(f"[{self.task.priority.value}]")
        self.priority_label.setAlignment(Qt.AlignCenter)
        self.priority_label.setFixedSize(40, 20)
        self.priority_label.setStyleSheet(self.get_priority_style())
        title_layout.addWidget(self.priority_label)
        
        title_layout.addStretch()
        info_layout.addLayout(title_layout)
        
        # 任务描述
        if self.task.description:
            self.description_label = QLabel(self.task.description)
            self.description_label.setWordWrap(True)
            desc_font = QFont()
            desc_font.setPointSize(9)
            self.description_label.setFont(desc_font)
            self.description_label.setStyleSheet("color: #666;")
            info_layout.addWidget(self.description_label)
        
        # 时间信息
        time_text = f"创建: {self.task.created_at.strftime('%Y-%m-%d %H:%M')}"
        if self.task.completed_at:
            time_text += f" | 完成: {self.task.completed_at.strftime('%Y-%m-%d %H:%M')}"
        
        self.time_label = QLabel(time_text)
        time_font = QFont()
        time_font.setPointSize(8)
        self.time_label.setFont(time_font)
        self.time_label.setStyleSheet("color: #999;")
        info_layout.addWidget(self.time_label)
        
        main_layout.addLayout(info_layout)
        
        # 按钮区域
        button_layout = QVBoxLayout()
        button_layout.setSpacing(4)
        
        # 编辑按钮
        self.edit_button = QPushButton("编辑")
        self.edit_button.setFixedSize(50, 25)
        self.edit_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 3px;
                font-size: 9px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        button_layout.addWidget(self.edit_button)
        
        # 删除按钮
        self.delete_button = QPushButton("删除")
        self.delete_button.setFixedSize(50, 25)
        self.delete_button.setStyleSheet("""
            QPushButton {
                background-color: #f44336;
                color: white;
                border: none;
                border-radius: 3px;
                font-size: 9px;
            }
            QPushButton:hover {
                background-color: #da190b;
            }
        """)
        button_layout.addWidget(self.delete_button)
        
        button_layout.addStretch()
        main_layout.addLayout(button_layout)
        
        self.setLayout(main_layout)
    
    def setup_connections(self):
        """设置信号连接"""
        self.checkbox.toggled.connect(lambda: self.task_toggled.emit(self.task.id))
        self.edit_button.clicked.connect(lambda: self.task_edit_requested.emit(self.task.id))
        self.delete_button.clicked.connect(lambda: self.task_delete_requested.emit(self.task.id))
    
    def get_priority_style(self) -> str:
        """获取优先级样式"""
        if self.task.priority == Priority.HIGH:
            return """
                background-color: #ff4444;
                color: white;
                border-radius: 10px;
                font-size: 8px;
                font-weight: bold;
            """
        elif self.task.priority == Priority.MEDIUM:
            return """
                background-color: #ffaa00;
                color: white;
                border-radius: 10px;
                font-size: 8px;
                font-weight: bold;
            """
        else:  # LOW
            return """
                background-color: #00aa00;
                color: white;
                border-radius: 10px;
                font-size: 8px;
                font-weight: bold;
            """
    
    def update_appearance(self):
        """更新外观"""
        if self.task.status == TaskStatus.COMPLETED:
            # 已完成任务的样式
            self.setStyleSheet("""
                TaskItem {
                    background-color: #f0f0f0;
                    border: 1px solid #ddd;
                    border-radius: 5px;
                }
            """)
            self.title_label.setStyleSheet("color: #888; text-decoration: line-through;")
            if hasattr(self, 'description_label'):
                self.description_label.setStyleSheet("color: #aaa; text-decoration: line-through;")
        else:
            # 待完成任务的样式
            self.setStyleSheet("""
                TaskItem {
                    background-color: white;
                    border: 1px solid #ddd;
                    border-radius: 5px;
                }
                TaskItem:hover {
                    border-color: #4CAF50;
                    background-color: #f9f9f9;
                }
            """)
            self.title_label.setStyleSheet("color: #333;")
            if hasattr(self, 'description_label'):
                self.description_label.setStyleSheet("color: #666;")
    
    def update_task(self, task: Task):
        """更新任务数据"""
        self.task = task
        self.title_label.setText(task.title)
        
        if hasattr(self, 'description_label'):
            if task.description:
                self.description_label.setText(task.description)
                self.description_label.show()
            else:
                self.description_label.hide()
        
        self.priority_label.setText(f"[{task.priority.value}]")
        self.priority_label.setStyleSheet(self.get_priority_style())
        
        self.checkbox.setChecked(task.status == TaskStatus.COMPLETED)
        
        # 更新时间信息
        time_text = f"创建: {task.created_at.strftime('%Y-%m-%d %H:%M')}"
        if task.completed_at:
            time_text += f" | 完成: {task.completed_at.strftime('%Y-%m-%d %H:%M')}"
        self.time_label.setText(time_text)
        
        self.update_appearance()